package br.com.fiap.trabalho.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import br.com.fiap.trabalho.entity.Studio;


public class JPAStudioDAO implements StudioDAO{

	private static EntityManager em = null;
	private Studio studio = null;
	
	
	public JPAStudioDAO(Studio studio) {
		this.studio = studio;
		em = createEntityManager();
	}

	private synchronized static EntityManager createEntityManager() {
		if(em==null){
			EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistenceUnit");
			em = emf.createEntityManager();
		}
		return em;
	}

	public Studio createStudio() {

		try{
			em.getTransaction().begin();
			em.persist(studio);
			em.getTransaction().commit();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
		return studio;
	}
	
	public List<Studio> selectStudioByName(String name) {

		Query query = em.createNativeQuery("SELECT * FROM STUDIO WHERE NAME = :paramName",Studio.class);
		query.setParameter("paramName", name);
		@SuppressWarnings("unchecked")
		List<Studio> listStudioByName = query.getResultList();
		
		return listStudioByName;
	}

	public Studio getStudio() {
		return studio;
	}

	public void setStudio(Studio studio) {
		this.studio = studio;
	}
}
